package com.hqyj.handler;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.hqyj.exception.JwtException;
import com.hqyj.utile.JwtUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 项目:demo-springboot-230701
 * 描述:
 * 时间:2023/9/28 10:54
 * 作者:admin
 * 版本:1.0
 **/
public class JwtHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws JwtException {
        //获取token
        String token = request.getHeader("Authorization");
        //1 判断是否为空
        if(StringUtils.isEmpty(token)){
            throw new JwtException("token不能为空","",300);
        }
        //2 验证token是否争取
        String id = JwtUtil.getAudience(token);
        if(id==null){
            throw new JwtException("token验证不正确","",300);
        }
        //3 验证token是否过期
       String jwtSalt= JwtUtil.getClaimByName(token,"jwtSalt").asString();
        DecodedJWT dd = JwtUtil.verifyToken(token,jwtSalt);
        if (dd==null){
            throw new JwtException("token过期","",300);
        }

        return true;
    }
}
